package sis.studentinfotest;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-07-28 15:58
 * @notify
 * @version 1.0
 */

import junit.framework.TestCase;
import sis.studentinfo.Student;
import sis.studentinfo.StudentUI;

import java.io.*;
import java.util.List;

public class StudentUITest extends TestCase {
    static private final String name = "Leo Xerces Schmoo";

    public void testCreateStudent() throws IOException {
        StringBuffer expectedOutput = new StringBuffer();
        StringBuffer input = new StringBuffer();
        setUp(expectedOutput, input);
        byte[] buffer = input.toString().getBytes();

        InputStream inputStream = new ByteArrayInputStream(buffer);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        OutputStream outputStream = new ByteArrayOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

        StudentUI ui = new StudentUI(reader, writer);
        ui.run();

        assertEquals(expectedOutput.toString(), outputStream.toString());
        assertStudents(ui.getAddedStudents());
    }



    public void testCreateStudent2() throws IOException {
        StringBuffer expectedOutput = new StringBuffer();
        StringBuffer input = new StringBuffer();
        setUp(expectedOutput, input);
        byte[] buffer = input.toString().getBytes();

        InputStream inputStream = new ByteArrayInputStream(buffer);
        OutputStream outputStream = new ByteArrayOutputStream();

        InputStream consoleIn = System.in;
        PrintStream consoleOut = System.out;
        System.setIn(inputStream);
        System.setOut(new PrintStream(outputStream));
        try{
            StudentUI ui = new StudentUI();
            ui.run();
            assertEquals(expectedOutput.toString(), outputStream.toString());
            assertStudents(ui.getAddedStudents());
        }finally {
            System.setIn(consoleIn);
            System.setOut(consoleOut);
        }

    }

    public static void main(String[] args)throws IOException {
        new StudentUI().run();
    }

    private String line(String input) {
        return String.format("%s%n", input);
    }

    private void setUp(StringBuffer expectedOutput, StringBuffer input) {
        expectedOutput.append(StudentUI.MENU);
        input.append(line(StudentUI.ADD_OPTION));
        expectedOutput.append(StudentUI.NAME_PROMPT);
        input.append(line(name));
        expectedOutput.append(line(StudentUI.ADDED_MESSAGE));
        expectedOutput.append(StudentUI.MENU);
        input.append(StudentUI.QUIT_OPTION);
    }

    private void assertStudents(List<Student> studentList) {
        assertEquals(1, studentList.size());
        Student student = studentList.get(0);
        assertEquals(name, student.getName());
    }


}
